const User = require('../models/user')

const response = require('../utils/response')

const jwt = require('jsonwebtoken')
const bcrypt = require('bcryptjs')
const { huanTime } = require('../utils/tool')

// 用户登录
exports.login = async (req, res, next) => {
    try {
        let {
            workerNumber,
            password
        } = req.body
        let data = await User.findOne({
            workerNumber
        }).populate('position rofessional').lean()

        //生成token
        const token = jwt.sign({
            id: data._id,
            ctime:parseInt(new Date().getTime() / 1000), //创建时间、当前时间
            expiresIn:60 * 60 * 24 //过期时间/1天 
            // expiresIn:1
        }, req.app.get('token'))
        
        data.password = '******'

        response(res, 200, '成功', {
            data,
            token
        })
    } catch (err) {
        next(err)
    }
}

// 工号
exports.worker = async (req, res, next) => {
    try {
        const count = await User.find().countDocuments()
        var worker = await User.find().skip(count - 1)
        var number = worker[0].workerNumber.toString().substr(4, 3)
        var year = worker[0].workerNumber.toString().substr(0, 4)
        var newNumber = Number(number) + 1
        var time = new Date();
        var y = time.getFullYear();
        if (y != year) {
            newNumber = 1
        }
        function add(m) {
            if (m < 10) {
                m = m.toString()
                return m = Number(y + '0' + '0' + m)
            }
            if ( m >= 10 && m < 100 ) {
                m = m.toString()
                console.log('aaa');
                return m = Number(y + '0' + m)
            }
            if (m >= 100) {
                m = m.toString()
                return m = Number(y + m)
            }
        }
        var newNumber = add(newNumber)
        response(res, 200, '成功', newNumber)
    } catch (err) {
        next(err)
    }
}

// 用户修改信息
exports.updatedUser = async (req,res,next) => {
    try {
        // const userId = req.params.userId
        let user = req.user
        user.phone = parseInt(req.body.phone) || parseInt(user.phone)
        user.email = req.body.email || user.email
        user.image = req.body.image || user.image

        //更正时间
        user.updatedAt = huanTime(Date.now())

        let model = await User.findByIdAndUpdate(user._id, user)
        user.password = "******"
        response(res, 200, '修改成功~~', user)
    } catch (error) {
        next(error)
    }
}

// 用户修改密码
exports.updatedPws = async (req,res,next) => {
    try {
        let {
            old_password,
            new_password,
        } = req.body

        let user = req.user
        let isEqual = await bcrypt.compare(old_password, user.password)
        if (!isEqual) return response(res, 401, '旧密码错误~~', null)
        // if (new_password !== p_new_password) return response(res, 402, '两次密码不一致~~', null)

        user.password = await bcrypt.hash(new_password, 10)

        //更正时间
        user.updatedAt = huanTime(Date.now())

        let model = await User.findByIdAndUpdate(user._id, user)

        // res.send(user)
        user.password = "******"
        response(res, 200, '修改成功~~', user)
    } catch (error) {
        next(error)
    }
}